﻿Imports System.Net
Imports System.Text.RegularExpressions

Public Class NicoLiveSite

    Public Property UserAgent As String


    Public Function IsClosed(ByVal program As LiveProgram) As Boolean

        Dim content = GetContent(program.Uri)
        Dim pattern =
            "<div id=""comment_arealv" & program.Id.ToString & """>\s*" &
            "この番組は.*?に終了いたしました。<br>\s*" &
            "<b>来場者数：</b>(?<visitor_count>\d+)人\s*<b>コメント数：</b>(?<comment_count>\d+)\s*<br /><br />\s*" &
            "</div>"

        Dim match = Regex.Match(content, pattern, RegexOptions.Singleline)
        If Not match.Success Then
            Return False
        End If

        program.VisitorCount = Convert.ToInt32(match.Groups("visitor_count").Value)
        program.CommentCount = Convert.ToInt32(match.Groups("comment_count").Value)
        program.IsOnAir = False
        Return True

    End Function

    Private Function GetContent(ByVal uri As Uri) As String

        Dim request = DirectCast(WebRequest.Create(uri), HttpWebRequest)
        request.UserAgent = UserAgent

        Dim content As String = ""
        Using response = request.GetResponse
            Using stream = New System.IO.StreamReader(response.GetResponseStream, System.Text.Encoding.UTF8)
                content = stream.ReadToEnd
            End Using
        End Using

        Return content

    End Function

End Class
